<?php
session_start();
?>
<html>
<?php
    
    if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
    // last request was more than 30 minates ago
    session_unset();     // unset $_SESSION variable for the runtime 
    session_destroy();   // destroy session data in storage
    
    $host  = $_SERVER['HTTP_HOST'];
    $uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
    $extra = 'index.php';
    header("Location: http://$host$uri/$extra?expire=true");
    exit;
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
?>     
    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Botany Dichotomous Key Conversion System</title>
        <link rel="stylesheet" type="text/css" href="css/default.css" />
        <link rel="stylesheet" type="text/css" href="css/stepsMenu.css" />
        
        <script src="javascripts/imageCheck.js"></script>
       
    </head>
        
<body>
    <script type="text/javascript" src="javascripts/jquery.js"></script>
    <script type="text/javascript" src="javascripts/addimage.js"></script>
            <?php 
            $uploaddir= $_POST["output"];
            $inputFile = $uploaddir."keyconversion.xml";
            $xml = simplexml_load_file($inputFile);
            $sxe = new SimpleXMLElement($xml->asXML());
            //This is the directory where images will be saved 
            $target = $uploaddir; 
            //$target = $target . basename( $_FILES['photo']['name']);
            
            //Upload Organism Images
            $Orgcount = count($xml->organisms->organism);
            //echo "Organism count = ".$Orgcount."<br />";
            for($i = 0; $i < $Orgcount; $i++){

                $orgButtonId = "org".$xml->organisms->organism[$i]->org_id."image";
                $organismNode = $sxe->organisms[0]->organism[$i];
                $elementName = "image";

                /**************************/
                $existImage = count($organismNode->image);
                if($existImage > 0){
                    unset($organismNode->image);
                }
                /**************************/
                
                //echo $orgButtonId;
                $imagecount = 0;

                
                foreach($_FILES["$orgButtonId"] as $key)
                {
                    $filename = "organism" . $xml->organisms->organism[$i]->org_id . $imagecount . ".png";
                    //echo "1 " . $imagecount . $filename . $orgButtonId. "<br>";
                    
                    if(!empty($_FILES["$orgButtonId"]["tmp_name"][$imagecount]) )
                    {
                        //echo "2 " . $imagecount . $filename . $orgButtonId. "<br>";

                        $splitName = explode(".", $_FILES["$orgButtonId"]["name"][$imagecount]); // Split file name into an array using the dot
                        $imgFileExt = end($splitName); // Now target the last array element to get the file extensio
                        if (strtolower($imgFileExt) != "png") {

                           imageConversion($orgButtonId,$filename,$imgFileExt, $imagecount);
                           $organismNode->addChild("image", $filename);
                        }

                        else{

                            move_uploaded_file($_FILES["$orgButtonId"]["tmp_name"][$imagecount],$uploaddir.$filename);
                            $organismNode->addChild("image", $filename); 
                        }
                    }
                    /*else {
                     $organismNode->addChild("image"); 

                    }*/
                    $imagecount++;
                }
            }//end of for
            
            
                // FOR PROPER FORMATTING XML
                // Create a new DOMDocument object
                $dom = new DOMDocument('1.0');
                // add spaces, new lines and make the XML more readable format        
                $dom->preserveWhiteSpace = false;
                $dom->formatOutput = true;
                //Load XML document from a string
                $dom->loadXML($sxe->asXML());
                //Save XML to file 
                $dom->save($inputFile);

                //Function to conver .jpg, .gif images to .png format
                function imageConversion($imgName,$newImage,$imgFileExt,$imagecount){
                    $imgFileTmpLoc = $_FILES["$imgName"]["tmp_name"][$imagecount]; // File in the PHP tmp folder
                    $new_png = $_POST["output"].$newImage;
                    $ext = strtolower($imgFileExt);
                    $new_img = "";
                    if ($ext == "gif"){ 
                        $new_img = imagecreatefromgif($imgFileTmpLoc);
                    } 
                    else if($ext =="jpg"){ 
                        $new_img = imagecreatefromjpeg($imgFileTmpLoc);
                    }
                    imagepng($new_img, $new_png);
                    //$organismNode->addChild("$elementName", "$newImage");
                    imagedestroy($imgFileTmpLoc);
                    
                }

        ?>
        
    <?php include("includes/header.php"); ?>
     <div id="page-wrap2">
                <div id="main-content">

                    <div id="left-col">
                        <?php include("includes/menuAddDecisionNodeImages.php"); ?>
                    </div><!-- end of left-col -->
                <div id = "right-col">
                    <h3>Step 4: Upload Decision Node Images</h3>
                    <form action="AddCharacteristics.php" method="post" enctype="multipart/form-data">
                        <fieldset id="imageField">
                            <p class="instruction">Please select only .PNG, .JPG and .GIF image files to upload using <i>"Add Image"</i> link. 
                                You can upload multiple images for each decision node. Uploading images for the decision nodes is optional.</p>
                            <?php
                                #$filename = $_POST["filename"];
                                #echo "$filename";
                                $inputFile = $uploaddir."keyconversion.xml";
                                $xml = simplexml_load_file($inputFile);
                                //echo $xml->getName() . "<br />";
                                //foreach($xml->children() as $child){
                                  //  echo $child->getName() . ": " .$child. "<br />";
                                //}
                                
                                $Nodecount = count($xml->nodes->Node);
                                //echo "Node count = ".$Nodecount."<br />";
                                echo "<div ID=\"nodes\">";
                                echo "<br /><h4><i> Decision Nodes </i></h4>";
                                echo"<table width=\"100%\" cellspacing=\"10\"><tr><td valign=\"top\">";
                                echo"<table class='decisionTable'>";
                                for($i = 0; $i < $Nodecount; $i++){
                                    if($xml->nodes->Node[$i]->isLeafNode == "no"){
                                        //echo"<br> <br>";
                                        echo "<tr><td>";
                                        echo $xml->nodes->Node[$i]->leftChildID. "&nbsp";
                                        echo $xml->nodes->Node[$i]->leftChildDescription."<br /><br />"; 
                                        $leftChildButtonId = "node".$xml->nodes->Node[$i]->leftChildID."image";
                                        echo "<a id=\"$leftChildButtonId\" href=\"#\">Add Image (1 or more)</a>";
                                        echo "<br><br>";
                                        echo "</td></tr>";
                                        //echo "</td>";

                                        //echo"<br> <br>";
                                        echo "<tr><td>";
                                        //echo "<td>";
                                        echo $xml->nodes->Node[$i]->rightChildID. "&nbsp";
                                        echo $xml->nodes->Node[$i]->rightChildDescription."<br /><br />"; 
                                        $rightChildButtonId = "node".$xml->nodes->Node[$i]->rightChildID."image";
                                        echo "<a id=\"$rightChildButtonId\" href=\"#\">Add Image (1 or more)</a>";
                                        echo "<br><br>";
                                        echo "</td></tr>";
                                        
                                        if($Nodecount % 2 == 0 )
                                        {
                                            if($i == $Nodecount/2)
                                            {
                                                echo"</table></td><td valign=\"top\">";
                                                echo"<table class='decisionTable'>";
                                            }
                                        }
                                        else 
                                        {
                                            if($i == ($Nodecount+1)/2)
                                            {
                                                echo"</table></td><td valign=\"top\">";
                                                echo"<table class='decisionTable'>";
                                            }                                        
                                        }
                                    }//end of if
                                }//end of for
                                echo"</table>";
                                echo"</td></tr></table>";
                                echo "</div>";
                            ?>
                            
                          <div style="text-align:center;">
                           <input type="hidden" name="output" value=<?php echo $uploaddir ?> /> <br/><br/>   
                            <input type="submit" class="next" value="Next"/> <br /><br />
                          </div>
                            
                        </fieldset>
                    </form>
                </div><!-- end of right-col -->
                <div class="clear"></div> <!-- all the content inside main-content div element is floated, need to clear float...
                                              because height of main-content does not know how tall it would be -->

            </div><!-- end of main-content -->        
        </div>  <!-- End of page-wrap -->                       
    <?php include("includes/footer.php"); ?>
</body>
</html> 

